<template>
  <div class="waterfall">
    <!-- 点击图片详情弹窗 --><!-- :open="opmethod" -->
    <el-dialog
      :visible.sync="dialogVisible"
      :fullscreen="false"
      custom-class="el-dialog-aa"
      width="65%"
      top="8vh"
      title="工 艺 品 详 情"
      :show-close="true"
      @open="opmethod"
    >
      <pic-detail
        ref="detailWin"
        :worksId="worksId"
        @closedialog="closedialog"
      ></pic-detail>
    </el-dialog>
    <!-- 公共搜索头部,管理页面不显示 -->
    <el-header>
      <search-header ref="searchBlock"></search-header>
    </el-header>

    <!-- 瀑布流主体 -->
    <loader v-show="isLoading" style="margin: 15% auto" />
    <div
      v-show="!isLoading"
      class="v-waterfall-content"
      id="v-waterfall"
      v-infinite-scroll="getMoreData"
      infinite-scroll-disabled="disabled"
      infinite-scroll-distance="10"
    >
      <!-- 回到顶部 -->
      <template>
        <el-backtop
          target=".v-waterfall-content"
          :visibility-height="10"
          :bottom="70"
          :right="60"
          style="background-color: transparent"
        >
          <img
            style="height: 120px"
            src="http://60.205.247.68:9001/image/top.png"
            alt=""
          />
        </el-backtop>
      </template>
      <div
        v-for="(img, index) in waterfallList"
        :key="index"
        class="v-waterfall-item"
        :style="{
          top: img.top + 'px',
          left: img.left + 'px',
          width: waterfallImgWidth + 'px',
          height: img.height,
        }"
      >
        <el-card
          style="width: 110%; padding: 7px"
          shadow="hover"
          :body-style="{ padding: '0px', 'border-radius': '10px' }"
          @click.native="openDialog(img.worksId)"
        >
          <el-image
            style="border-radius: 5px"
            :src="imgUrl + img.worksImage"
            class="image"
            :key="img.worksId"
            lazy
          />
          <p style="font-size: 1.2rem; color: #4f4f4f; margin: 4px 4px 4px 9px">
            {{ img.title }}
          </p>
          <p
            style="
              font-size: 0.75rem;
              color: #6e6e6e;
              margin-left: 9px;
              padding-bottom: 6px;
            "
          >
            工艺指数：
          </p>
          <el-rate
            v-model="img.worksScore"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}"
            style="margin-left: 9px"
          >
          </el-rate>
          <p
            style="
              font-size: x-small;
              color: #918787;
              margin: 4px 9px 15px 9px;
              padding-bottom: 6px;
              text-indent: 1.5rem;
              line-height: 1.8em;
              letter-spacing: 1px;
            "
          >
            {{ img.worksProfile }}
          </p>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import PicDetail from "@/components/works/PicDetail";
import SearchHeader from "@/components/SearchHeader";
import Loader from "../loaders/Loader.vue";
export default {
  name: "Consultation",
  components: {
    PicDetail,
    SearchHeader,
    Loader,
  },
  data() {
    return {
      imgUrl: this.$imageUrl,
      // 初始页
      currentPage: 1,
      // 是否还有数据
      noMore: false,
      // 难度系数
      value: "",
      // 图片详情弹窗可见
      dialogVisible: false,
      // 等待服务器响应
      isLoading: true, 
      // 加载完数据
      noMore: false,
      worksId: "",
      // 搜索数据
      searchParams: "",

      waterfallList: [],
      // waterfallImgWidth: 100,
      waterfallImgWidth: 200, // 每个盒子的宽度
      // waterfallImgCol: 5,// 瀑布流的列数
      waterfallImgCol: 4, // 瀑布流的列数
      waterfallImgRight: 60, // 每个盒子的右padding
      waterfallImgBottom: 10, // 每个盒子的下padding
      waterfallDeviationHeight: [],
      imgList: [],
    };
  },

  created() {
    //初始就加载数据
    this.getMoreData();
  },
  mounted() {
    this.$refs.searchBlock.$on("searchInput", this.searchOn);
    this.calculationWidth();
  },
  methods: {
    //计算每个图片的宽度或者是列数
    calculationWidth() {
      let domWidth = document.getElementById("v-waterfall").offsetWidth;
      if (!this.waterfallImgWidth && this.waterfallImgCol) {
        this.waterfallImgWidth =
          (domWidth - this.waterfallImgRight * this.waterfallImgCol) /
          this.waterfallImgCol;
      } else if (this.waterfallImgWidth && !this.waterfallImgCol) {
        this.waterfallImgCol = Math.floor(
          domWidth / (this.waterfallImgWidth + this.waterfallImgRight)
        );
      }
      //初始化偏移高度数组
      this.waterfallDeviationHeight = new Array(this.waterfallImgCol);
      for (let i = 0; i < this.waterfallDeviationHeight.length; i++) {
        this.waterfallDeviationHeight[i] = 0;
      }
      this.imgPreloading();
    },
    //搜索接收参数
    searchOn(params) {
      console.log("收到了搜索参数：", params);
      this.currentPage = 1;
      for (let i = 0; i < this.waterfallDeviationHeight.length; i++) {
        this.waterfallDeviationHeight[i] = 0;
      }
      this.waterfallList = [];
      this.searchParams = params;
      this.getMoreData();
    },
    // 获取数据
    getMoreData() {
      //表单数据
      let param = {
        pageNo: this.currentPage++,
        pageSize: 10,
        order: "update_time desc",
        type: "",
        name: "",
      };
        this.isLoading = true;
      console.log("搜索参数searchParams：", this.searchParams);
      let search = this.searchParams;
      if (search !== "") {
        param.type = search.type.replace("  ", "");
        param.name = search.name.trim();
      }
      console.log("查询后端参数：" + JSON.stringify(param));
      this.$axios
        .get("/works/worksExhibit", {
          params: param,
        })
        .then((res) => {
          this.isLoading = false;
          console.log("获取数据", res.data);
          if (res.data.status == 200) {
            if (res.data.data.records.length == 0) {
              this.noMore = true;
            } else {
              this.imgPreloading(res.data.data.records);
              this.noMore = false;
            }
          } else {
            this.$message.error(res.data.msg);
            this.noMore = true;
          }
        })
        .catch(() => {
          this.$message.error("服务器请求失败！");
        });
    },

    //图片预加载
    imgPreloading(recordsList) {
      for (let i = 0; i < recordsList.length; i++) {
        const record = Object.assign({}, recordsList[i]);
        let aImg = new Image();
        aImg.src = this.imgUrl + recordsList[i].worksImage;
        aImg.onload = aImg.onerror = (e) => {
          let imgData = {
            ...record,
          };
          imgData.height = (this.waterfallImgWidth / aImg.width) * aImg.height;
          imgData.src = this.imgUrl + recordsList[i].worksImage;
          imgData.title = recordsList[i].worksName; // 说明文字（也可以自己写数组，或者封装json数据，都可以，但是前提是你会相关操作，这里不赘述）
          imgData.info = recordsList[i].worksProfile; // 说明文字,工艺简介
          this.waterfallList.push(imgData);
          this.rankImg(imgData);
        };
      }
    },
    //瀑布流布局
    rankImg(imgData) {
      let {
        waterfallImgWidth,
        waterfallImgRight,
        waterfallImgBottom,
        waterfallDeviationHeight,
        waterfallImgCol,
      } = this;
      let minIndex = this.filterMin();
      imgData.top = waterfallDeviationHeight[minIndex];
      imgData.left = minIndex * (waterfallImgRight + waterfallImgWidth);
      // waterfallDeviationHeight[minIndex] += imgData.height + waterfallImgBottom;// 不加文字的盒子高度
      waterfallDeviationHeight[minIndex] +=
        imgData.height + waterfallImgBottom + 200; // 加了文字的盒子高度，留出文字的地方（这里设置56px）
      console.log(imgData);
    },
    /**
     * 找到最短的列并返回下标
     * @returns {number} 下标
     */
    filterMin() {
      const min = Math.min.apply(null, this.waterfallDeviationHeight);
      return this.waterfallDeviationHeight.indexOf(min);
    },

    //打开图片详情
    openDialog(worksId) {
      this.worksId = worksId;
      this.dialogVisible = true;
      // this.$refs.detailWin.getWorksInfo();
    },
    opmethod() {
      //打开Dialog时执行的回调，延迟加载详情页的数据，避免子组件的方法没找到
      setTimeout(() => {
        this.$refs.detailWin.getWorksInfo();
      }, 10);
    },
    closedialog() {
      //关闭弹窗
      this.dialogVisible = false;
    },
  },
  computed: {
    disabled() {
      return this.noMore;
    },
  },
};
</script>

<style scoped>
.waterfall {
  background-size: cover;
  background-image: url('~@/assets/bg.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  width: 100%;
  height: 92vh;
  position: relative;
  overflow: hidden;
}
.v-waterfall-content {
  /* background-color: coral; */
  /* 主要 */
  width: 90%;
  height: 81.7vh;
  overflow: hidden;
  left: 15%;
  position: relative;
  /* 次要：设置滚动条，要求固定高度 */
  overflow-y: auto;
}

.v-waterfall-item {
  /* background-color: grey; */
  /* 主要 */
  float: left;
  position: absolute;
}

.v-waterfall-item img {
  /* 主要 */
  width: 100%;
  height: auto;
  /* 次要 */
  border-radius: 6px;
}
</style>
